package BIO.chat_demo;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class ServerReaderThread extends Thread{
    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
           //1.从socket中获取当前客户端的输入流
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String msg;
            while ((msg = br.readLine()) != null){
                //2.服务端接收到了客户端的消息之后，需要推送给当前的所有在线socket
                sendMsgToAllClient(msg);
            }
        }catch (Exception e){
            System.out.println("当前有人下线!");
            //从在线socket集合中移除本socket
            Server.socketList.remove(socket);
        }
    }

    /**
     * 把当前客户端发送来的消息推送给全部的在线socket
     * @param msg
     */
    private void sendMsgToAllClient(String msg) throws IOException {
        for (Socket socket : Server.socketList) {
            OutputStream outputStream = socket.getOutputStream();
            PrintStream ps = new PrintStream(outputStream);
            ps.println(msg);
            ps.flush();
        }
    }


}
